package com.qiniu.uploadtest.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.uploadtest.entity.QiNiu;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.InputStream;



@Component
public class UploadFileUtils {

    @Autowired
    private QiNiu qiNiu;

    public Response uploadFile(InputStream fileInputStream, String fileName){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        try {
            Auth auth = Auth.create(qiNiu.getAccesskey(), qiNiu.getSecretkey());
            String upToken = auth.uploadToken(qiNiu.getBucket());
            try {
                Response response = uploadManager.put(fileInputStream,key,upToken,null, null);
                //解析上传成功的结果
                return  response;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            //ignore
            e.printStackTrace();
        }
        return  null;
    }

}
